package com.miya.demo.support.rabbitmq.delay;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.miya.demo.support.rabbitmq.dto.DelayDemoLetterDTO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 延迟demo侦听器
 *
 * @author Caixiaowei
 * @date 2022/08/08
 */
@Component
@Slf4j
public class DelayDemoListener {

    @RabbitListener(queues = DelayDemoConfig.DELAY_QUEUE)
    public void onMessage(Message message, Channel channel) throws IOException {
        String sourstring = new String(message.getBody(), StandardCharsets.UTF_8);
        DelayDemoLetterDTO dto = JSONUtil.toBean(sourstring, DelayDemoLetterDTO.class);
        log.info("延迟demo消费: {}, 接收时间: {}", sourstring, DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATETIME_PATTERN));
        try {
            // todo 具体延时队列业务
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("延迟demo消费 异常: {}", sourstring);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }

    }
}
